<template>
  <a-upload
    name="file"
    :multiple="true"
    :action="uploadAction"
    :headers="headers"
    :data="{data:content}"
    :fileList="fileList"
    @change="handleChange"
    @preview="handlePreview"
  >
    <a-button v-if="fileList.length==0"> <a-icon type="upload" /> {{ text }}</a-button>
  </a-upload>
</template>

<script>
  import Vue from "vue";
  import api from '@/api/api'

const uidGenerator = () => {
  return "-" + parseInt(Math.random() * 10000 + 1, 10);
};
const getFileName = (path) => {
  if (path.lastIndexOf("\\") >= 0) {
    let reg = new RegExp("\\\\", "g");
    path = path.replace(reg, "/");
  }
  return path.substring(path.lastIndexOf("/") + 1);
};
export default {
  name: "uploadFile",
  data() {
    return {
      uploadAction: api.url.uploadFile,
      uploadLoading: false,
      picUrl: false,
      headers: {},
      fileList: [],
      previewImage: "",
      previewVisible: false,
      bizData: {},
      // filesList:[]
    };
  },
  props: {
    text: {
      type: String,
      required: false,
      default: "上传",
    },
    /*这个属性用于控制文件上传的业务路径*/
    bizPath: {
      type: String,
      required: false,
      default: "aiinbi",
    },
    bizValue: {
      type: String,
      required: false,
    },
    content: {
      type: String,
      required: false,
    },
    fileListValue: {
      type: String,
      required: false,
      default:''
    },
    value: {
      type: [String, Array],
      required: false,
    },
    disabled: {
      type: Boolean,
      required: false,
      default: false,
    },
    isMultiple: {
      type: Boolean,
      required: false,
      default: false,
    },
    maxLength: {
      type: String,
      required: false,
    },
  },
  watch: {

    value(val) {
      //console.error("aaaaaaaaaa")
      if (val instanceof Array) {
        this.initFileList(val.join(","));
      } else {
        this.initFileList(val);
      }
    },
  },
  created() {
    //console.error("aaa",this.fileListValue)
    this.initFileList(this.fileListValue)
  },
  methods: {
    getFileAccessHttpUrl (avatar, subStr) {
      if (!subStr) subStr = 'http'
      if (avatar && avatar.startsWith(subStr)) {
        return avatar
      } else {
        if (avatar && avatar.length > 0 && avatar.indexOf('[') == -1) {
          return window._CONFIG['staticDomainURL'] + '/' + avatar
        }
      }},
    initFileList(paths) {
      if (!paths || paths.length == 0 || paths == undefined) {
        this.picUrl = false;
        this.fileList = [];
        return;
      }
      this.picUrl = true;
      let fileList = [];
      let arr = paths.split(",");
      for (var a = 0; a < arr.length; a++) {
        let url = this.getFileAccessHttpUrl(arr[a]);
        fileList.push({
          uid: uidGenerator(),
          name: getFileName(arr[a]),
          status: "done",
          url: url,
          response: {
            status: "history",
            message: arr[a],
          },
        });
      }
      this.fileList = fileList;
    },
    beforeUpload: function (file) {
      return true;
    },
    handleChange(info) {
      this.picUrl = false;
      let fileList = info.fileList;
      if (info.file.status === "done") {
        // debugger;
        if (info.file.response.success) {
          // alert(info.file.response);
         // console.info(info.file.response);
          info.file.response.message = info.file.response.data.url;
          this.picUrl = true;
          fileList = fileList.map((file) => {
            if (file.response) {
              file.url = file.response.message;
            }
            return file;
          });
        }
        //this.$message.success(`${info.file.name} 上传成功!`);
      } else if (info.file.status === "error") {
        this.$message.error('上传失败');
      } else if (info.file.status === "removed") {
        this.handleDelete(info.file);
      }
      this.fileList = fileList;

      if (this.fileList.length >= this.maxLength) {
        this.disabled = true;
      }
      if (info.file.status === "done" || info.file.status === "removed") {
        this.handlePathChange();
      }
    },

    // 预览
    handlePreview(file) {
      this.previewImage = file.url || file.thumbUrl;
      this.previewVisible = true;
    },
    getAvatarView() {
      if (this.fileList.length > 0) {
        let url = this.fileList[0].url;
        //console.error(url)
        return this.getFileAccessHttpUrl(url);
      }
    },
    handlePathChange() {
      let uploadFiles = this.fileList;
      let path = "";
      if (!uploadFiles || uploadFiles.length == 0) {
        path = "";
      }
      let arr = [];
      if (!this.isMultiple) {
        arr.push(uploadFiles[uploadFiles.length - 1].response.message);
      } else {
        for (var a = 0; a < uploadFiles.length; a++) {
          arr.push(uploadFiles[a].response.message);
        }
      }
      if (arr.length > 0) {
        path = arr.join(",");
      }
      this.$emit("change", path);
    },
    handleDelete(file) {
      //如有需要新增 删除逻辑
      console.log(file);
    },
    handleCancel() {
      this.close();
      this.previewVisible = false;
    },
    close() {},
  },
  model: {
    prop: "value",
    event: "change",
  },
};
</script>

<style scoped>
</style>
